package com.rizzo.analytics.worker.amqp.rabbit.listener;

import com.google.gag.annotation.remark.WhosYour;
import com.google.gag.enumeration.FamilyMember;
import com.rizzo.infrastructure.amqp.rabbit.log4j.LogStatement;
import com.rizzo.infrastructure.redis.config.RedisConfigManager;
import com.rizzo.infrastructure.redis.key.RedisKey;
import com.rizzo.infrastructure.redis.key.RedisKeyBuilder;
import com.rizzo.infrastructure.redis.timeseries.TimeStep;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

@WhosYour(value = FamilyMember.DADDY)
public class LogStatementBroker {

    private RedisTemplate<RedisKey, String> performanceRedisTemplate;
    private RedisConfigManager redisConfigManager;

    public void onLogStatement(LogStatement logStatement) throws Exception {
        RedisKey redisKey = new RedisKey(logStatement);
        switch (logStatement.getType()) {
            case PERFORMANCE:
                if (this.performanceRedisTemplate != null) {
                    // set the new "appending" performance
                    // from the logStatementTimestamp variable we want to get the timestep id it falls in
                    // on the other end we want to do getrange on the value
                    String logStatementTimestamp = String.valueOf(logStatement.getTimestamp());
                    String newPrincipal = (StringUtils.hasText(logStatement.getPrincipal()) ? logStatement.getPrincipal() : RedisKey.ANONYMOUS);
                    Period performanceTimeStep =
                            TimeStep.parsePeriod(redisConfigManager.getUserConfig(newPrincipal, redisKey.getApplication(), "performanceTimeStep"));
                    String performanceDurationZeroPaddings =
                            redisConfigManager.getSystemConfig("performanceDurationZeroPaddings");
                    RedisKey appendingPerformanceKey = new RedisKeyBuilder(redisKey).data(newPrincipal)
                            .data(TimeStep.encodeTimeStep(new DateTime(logStatement.getTimestamp()), performanceTimeStep)).build();
                    String durationPadded =
                            String.format("%0" + performanceDurationZeroPaddings + "d", Integer.valueOf(logStatement.getDuration()));
                    performanceRedisTemplate.opsForValue().append(appendingPerformanceKey, logStatementTimestamp + durationPadded);
                }
                break;
        }
    }

    public void setPerformanceRedisTemplate(RedisTemplate<RedisKey, String> performanceRedisTemplate) {
        this.performanceRedisTemplate = performanceRedisTemplate;
    }

    public void setRedisConfigManager(RedisConfigManager redisConfigManager) {
        this.redisConfigManager = redisConfigManager;
    }
}
